import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginCode } from '@/service/index/login'

const initState = { nickname: '', avatar: '' }

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })

    // 企微code授权登录
    const login = async (code) => {
      return new Promise(function (resolve, reject) {
        loginCode(code)
          .then((res) => {
            if (res.code === 200) {
              // #ifdef H5
              setToken(res.token)
              // #endif
              resolve(res.data)
            } else {
              reject(res)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
      removeToken()
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }

    const isLogined = computed(() => !!getToken())

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLogined,
      setToken,
      reset,
      login,
    }
  },
  {
    persist: true,
  },
)
